/**
 * 
 */
package PagedFile;

import java.nio.ByteBuffer;

/**
 * @author Neil
 * A good file structure is the prerequisite of a good implementation.
 * My design of the structure is as follows:
 * index(page)	name			contents
 * 0	 		PF_FileHead 	number of pages allocated
 * 								last page num 
 * 								(it's equal to nAllocatedPages-1,
 * 								or maybe greater when page has been disposed)
 * 								bitmap to find allocated pages
 * 1			RM_FileHead		number of records stored in the file
 * 								record size
 * 								number of records per page
 * 								first record offset
 * 								bitmap to find full pages
 * 2-			Data Pages		PageHead -- number of records in the page
 * 								bitmap for records in the page to find allocated records
 * 								list of records
 */
public class PF_FileHead {
	public int nAllocatedPages;
	public int lastPageNum;
	public byte[] bitmap;
	public static final int PF_FILEHEAD_SIZE=8;
	public static final int PF_BMAPBITS = Buffer.BLOCK_SIZE-PF_FILEHEAD_SIZE;
	static FunctionalClass.Bit_Operation bop = new FunctionalClass.Bit_Operation();
	
	public PF_FileHead(int lpn, int nap){
		init_bitmap();
		this.lastPageNum = lpn;
		this.nAllocatedPages = nap;
	}
	
	public PF_FileHead(ByteBuffer bb){
		init_bitmap();
		get_from_ByteBuffer(bb);
	}
	
	public String toString(){
		String ret = "(";
		ret += nAllocatedPages + ", ";
		ret += lastPageNum;
/*		for (int i=0; i<MAXPAGES*8; ++i) 
			if ( bop.bitTest(bitmap, i) )
				ret += "1";
			else
				ret += "0";
*/		ret += ")";
		return ret;
	}

	public void put_into_ByteBuffer(ByteBuffer bb) {
		bb.position(0);
		bb.putInt(nAllocatedPages);
		bb.putInt(this.lastPageNum);
		for (int i=0; i<PF_BMAPBITS; ++i)
			bb.put(bitmap[i]);
	}
	
	public void get_from_ByteBuffer(ByteBuffer bb) {
		bb.position(0);
		nAllocatedPages = bb.getInt();
		lastPageNum = bb.getInt();
		for (int i=0; i<PF_BMAPBITS; ++i)
			bitmap[i] = bb.get();
	}
	
	private void init_bitmap() {
		bitmap = new byte[PF_BMAPBITS];
		bop.bitSet(bitmap, 0);
	}
}
